package com.scheudler.demo.quartz;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

/**
 * @author dongqun
 * @version 1.0
 * @description 类的功能描述
 * @date 2019/9/24 14:13
 */
@Component
public class TaskService {
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    /**
     * @author dongqun
     * @description  触发器-->--  调度器  --<-- 作业 --<-- 定时任务
     * @date 2019/9/24 15:10
     * @param
     * @return
     */
    public void execute(ScheduleJob task){
        try {
            //1、不依赖spring
//            StdSchedulerFactory factory = new StdSchedulerFactory();
//            Scheduler scheduler = factory.getScheduler();
            //2、spring集成quartz
            Scheduler scheduler = schedulerFactoryBean.getScheduler();
            //添加触发调度名称
            TriggerKey triggerKey = TriggerKey.triggerKey(task.getJobName());
            //设置触发时间
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(task.getCronExpression());
            //触发建立
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(cronScheduleBuilder).build();
            //添加作业名称
            JobKey jobKey = JobKey.jobKey(task.getJobName());
            //建立作业
            JobDetail jobDetail = JobBuilder.newJob(QuartzFactory.class).withIdentity(jobKey).build();
            //传入调度的数据，在QuartzFactory中需要使用
            jobDetail.getJobDataMap().put("scheduleJob",task);
            //TODO 不依赖spring环境的话，要手动启动scheduler
            scheduler.start();
            //调度作业
            scheduler.scheduleJob(jobDetail,trigger);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}
